<template>
  <div class="page-root">
    <h2 class="main-title">健康管家管理</h2>
    <!-- 查询区域 -->
    <el-form :inline="true" :model="query" class="search-bar">
      <el-form-item label="用户名">
        <el-autocomplete
          v-model="query.username"
          :fetch-suggestions="queryUsernames"
          placeholder="请输入用户名"
          clearable
          style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="query.phone" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchUsers">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
      <el-form-item style="margin-left: auto;">
        <el-button type="success" @click="addDialogVisible = true">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 用户表格 -->
    <el-table
      :data="users"
      border
      style="width:100%; margin-top:2%; background:#f5f7fa;"
      :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column prop="username" label="用户名" min-width="18%" />
      <el-table-column prop="phone" label="手机号" min-width="18%" />
      <el-table-column prop="role" label="角色" min-width="18%" />
      <el-table-column label="操作" min-width="22%">
        <template #default="scope">
          <el-button size="small" @click="onEdit(scope.row)">详情</el-button>
          <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-bar">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增健康管家"
      width="420px"
      @close="onAddClose"
      draggable
    >
      <AddUserForm @success="onAddSuccess" />
    </el-dialog>
    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑健康管家"
      width="420px"
      @close="onEditClose"
      draggable
    >
      <EditUserForm :user="editUser" @success="onEditSuccess" />
    </el-dialog>
  </div>
</template>

<script setup>
import { inject, ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import qs from 'qs'
import AddUserForm from '@/components/userManage/AddUserForm.vue'
import EditUserForm from '@/components/userManage/EditUserForm.vue'

const axios = inject('axios')

const users = ref([])
const query = reactive({ username: '', phone: '' })
const pagination = reactive({ page: 1, size: 10, total: 0 })

const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const editUser = ref(null)

// 存储所有用户名
const allNames = ref([])

const fetchAllNames = async () => {
  try {
    const res = await axios.get('/user/listAllName')
    allNames.value = res.data.data || []
  } catch (e) {
    allNames.value = []
  }
}

// 自动补全建议
const queryUsernames = (queryString, cb) => {
  if (!queryString) {
    cb(allNames.value.map(name => ({ value: name })))
    return
  }
  const results = allNames.value
    .filter(name => name.includes(queryString))
    .map(name => ({ value: name }))
  cb(results)
}

const fetchUsers = async () => {
  const res = await axios.get('/user/pageCaretakers', {
    params: { ...query, page: pagination.page, size: pagination.size }
  })
  users.value = res.data.data || []
  pagination.total = res.data.total || 0
}

const onReset = () => {
  query.username = ''
  query.phone = ''
  pagination.page = 1
  fetchUsers()
}
const onPageChange = (p) => { pagination.page = p; fetchUsers() }
const onSizeChange = (s) => { pagination.size = s; pagination.page = 1; fetchUsers() }

const onAddClose = () => {}
const onEditClose = () => { editUser.value = null }

const onAddSuccess = () => {
  addDialogVisible.value = false
  fetchUsers()
}
const onEditSuccess = () => {
  editDialogVisible.value = false
  fetchUsers()
}
const onEdit = (row) => {
  editUser.value = { ...row }
  editDialogVisible.value = true
}
const onDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '删除确认', {
    type: 'warning'
  }).then(async () => {
    row.role = "停用"
    await axios.post('/user/update', qs.stringify(row))
    ElMessage.success('删除成功')
    fetchUsers()
  }).catch(() => {})
}

// 初始化
fetchAllNames()
fetchUsers()
</script>

<style scoped>
.page-root {
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
  padding: 0 3%;
}

.main-title {
  font-size: 27.2px;
  font-weight: bold;
  color: #333;
  margin-top: 0;
  margin-bottom: 2%;
}

.search-bar {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 1.2em;
  margin-bottom: 1.5%;
  align-items: center;
}

.el-table {
  background: #f5f7fa;
}

.pagination-bar {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 2%;
  margin-bottom: 2%;
}
</style>
